package util

import (
	"Graphite/database"
	"Graphite/model"
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"strconv"
	"strings"
)

//封装添加类

func AddBasic(res interface{}, col string) interface{} {
	db := database.GetMongoDB()
	collection := db.Collection(col)
	createResult, err := collection.InsertOne(context.Background(), res)
	if err != nil {
		log.Println(err)
	}

	return createResult.InsertedID
}

//封装方法调各表的数据信息

func GetMessage(key string, col string, page int64, per_page int64) interface{} {
	db := database.GetMongoDB()
	Collection := db.Collection(col)
	var findoptions *options.FindOptions
	if per_page > 0 {
		findoptions = &options.FindOptions{}
		findoptions.SetLimit(per_page)             //每页数据数量
		findoptions.SetSkip(per_page * (page - 1)) //根据第几页跳过数据
	}
	cur, err := Collection.Find(context.Background(), bson.M{"$or": []bson.M{{"batch_number": primitive.Regex{Pattern: key}},
		{"creator": primitive.Regex{Pattern: key}}}}, findoptions) //搜索空字符串得到全部数据
	if err != nil {
		log.Println(err)
	}
	if err := cur.Err(); err != nil {
		log.Println(err)
	}
	var all []bson.M
	err = cur.All(context.Background(), &all)
	if err != nil {
		log.Println(err)
	}
_:
	cur.Close(context.Background())
	fmt.Println("-----------")
	return all
}

//unique用
func GetMessage2(key string, col string, page int64, per_page int64) interface{} {
	db := database.GetMongoDB()
	Collection := db.Collection(col)
	var findoptions *options.FindOptions
	if per_page > 0 {
		findoptions = &options.FindOptions{}
		findoptions.SetLimit(per_page)             //每页数据数量
		findoptions.SetSkip(per_page * (page - 1)) //根据第几页跳过数据
	}
	if key == "" {
		str := ""
		cur, err := Collection.Find(context.Background(), bson.M{"creator": primitive.Regex{Pattern: str}}, findoptions) //搜索空字符串得到全部数据
		if err != nil {
			log.Println(err)
		}

		if err := cur.Err(); err != nil {
			log.Println(err)
		}
		var all []bson.M
		err = cur.All(context.Background(), &all)
		if err != nil {
			log.Println(err)
		}
	_:
		cur.Close(context.Background())
		fmt.Println("-----------")
		return all
	} else {
		cur, err := Collection.Find(context.Background(), bson.M{"unique": key}, findoptions) //搜索空字符串得到全部数据
		if err != nil {
			log.Println(err)
		}

		if err := cur.Err(); err != nil {
			log.Println(err)
		}
		var all []bson.M
		err = cur.All(context.Background(), &all)
		if err != nil {
			log.Println(err)
		}
	_:
		cur.Close(context.Background())
		fmt.Println("-----------")
		return all
	}
}

//得到调信息条数方法封装

func GetCount(col string, key string) int64 {
	db := database.GetMongoDB()
	collection := db.Collection(col)
	total_count, err := collection.CountDocuments(context.Background(), bson.M{"$or": []bson.M{{"batch_number": primitive.Regex{Pattern: key}},
		{"creator": primitive.Regex{Pattern: key}}}})
	if err != nil {
		log.Println(err)
	}

	return total_count
}

//unique用

func GetCount2(col string, key string) int64 {
	db := database.GetMongoDB()
	collection := db.Collection(col)
	if key == "" {
		total_count, err := collection.CountDocuments(context.Background(), bson.M{"creator": primitive.Regex{Pattern: key}})
		if err != nil {
			log.Println(err)
		}
		return total_count
	} else {
		total_count, err := collection.CountDocuments(context.Background(), bson.M{"unique": key})
		if err != nil {
			log.Println(err)
		}
		return total_count
	}
}

//得到搜索条数

func GetProCount(col string, key string) int64 {
	db := database.GetMongoDB()
	collection := db.Collection(col)
	total_count, err := collection.CountDocuments(context.Background(), bson.M{"task": primitive.Regex{Pattern: key}})
	if err != nil {
		log.Println(err)
	}

	return total_count
}

//删除
func Delete(id string, col string) interface{} {
	db := database.GetMongoDB()
	collection := db.Collection(col)
	objID, err := primitive.ObjectIDFromHex(id)
	deleteResult, err := collection.DeleteOne(context.Background(), bson.M{"_id": objID})
	if err != nil {
		log.Println(err)
	}
	fmt.Println(deleteResult)
	return deleteResult
}
//删除
func Delete2(c *gin.Context,id string, col string) interface{} {
	db := database.GetMongoDB()
	collection := db.Collection(col)
	var one model.Amount
	objID, err := primitive.ObjectIDFromHex(id)
	err =collection.FindOne(context.Background(), bson.M{"_id": objID}).Decode(&one)
	if err != nil {
		log.Println(err)
	}
	if one.Diameter=="次品"{
		Result1,err:=collection.DeleteOne(context.Background(),bson.M{"_id": objID})
		if err != nil {
			log.Println(err)
		}
		fmt.Println("amount:----",Result1)
		Result2,err:=db.Collection("weight").DeleteOne(context.Background(),bson.M{"time_stamp":one.Time_Stamp})
		if err != nil {
			log.Println(err)
		}
		fmt.Println("weight:----",Result2)
		return "成功"
	}

	//从汇总表中删除
	CargoSummary := db.Collection("CargoSummary")
	Weight := db.Collection("weight")
	var wei model.Weight
	var cargo model.CargoSummary
	err =Weight.FindOne(context.Background(), bson.M{"time_stamp": one.Time_Stamp}).Decode(&wei)
	parts := strings.SplitN(wei.Diameter, "Φ", 2)
	diameter, err := strconv.ParseInt(parts[1], 10, 64)
	
	if diameter >= 400 || diameter == 250 {
		parts := strings.SplitN(wei.Process_Length, "-", 2)
		var tmp = wei.Diameter + parts[0]
		err = CargoSummary.FindOne(context.Background(), bson.M{"process_specifications": tmp}).Decode(&cargo)
		t1,_ := strconv.ParseFloat(fmt.Sprintf("%.1f",wei.Finish_Product ), 64)
		t2,_ :=strconv.ParseFloat(fmt.Sprintf("%.1f",wei.RoughCast ), 64)
		t3,_ :=strconv.ParseFloat(fmt.Sprintf("%.1f",wei.Second_Burn + wei.Second_Burn_Furnace ), 64)
		t4,_ :=strconv.ParseFloat(fmt.Sprintf("%.1f",wei.Once_Dip ), 64)
		t5,_ :=strconv.ParseFloat(fmt.Sprintf("%.1f",wei.Once_Burn), 64)
		t6,_ :=strconv.ParseFloat(fmt.Sprintf("%.1f", wei.Once_Burn_Furnace + wei.Green_Body), 64)
		cargo.Finish_Product = cargo.Finish_Product - t1
		cargo.RoughCast = cargo.RoughCast - t2
		cargo.Second_Burn = cargo.Second_Burn - t3
		cargo.Once_Dip = cargo.Once_Dip - t4
		cargo.Once_Burn = cargo.Once_Burn - t5
		cargo.Green_Body = cargo.Green_Body - t6
		cargo.Time_Stamp = wei.Time_Stamp
		cargo.Diameter = wei.Diameter
		UpdateOne1(c,"CargoSummary",cargo,"_id",cargo.Id)
	} else {
		switch diameter {
		case 350,300,200:
			{
				var  tmp string
				if wei.Process_Length == "RP"{
					tmp = wei.Diameter + "RP"
				}else {
					parts := strings.SplitN(wei.Process_Length, "-", 2)
					tmp = wei.Diameter + parts[0]
				}
				err = CargoSummary.FindOne(context.Background(), bson.M{"process_specifications": tmp}).Decode(&cargo)
				t1,_ := strconv.ParseFloat(fmt.Sprintf("%.1f",wei.Finish_Product ), 64)
				t2,_ :=strconv.ParseFloat(fmt.Sprintf("%.1f",wei.RoughCast ), 64)
				t3,_ :=strconv.ParseFloat(fmt.Sprintf("%.1f",wei.Second_Burn + wei.Second_Burn_Furnace ), 64)
				t4,_ :=strconv.ParseFloat(fmt.Sprintf("%.1f",wei.Once_Dip ), 64)
				t5,_ :=strconv.ParseFloat(fmt.Sprintf("%.1f",wei.Once_Burn), 64)
				t6,_ :=strconv.ParseFloat(fmt.Sprintf("%.1f", wei.Once_Burn_Furnace + wei.Green_Body), 64)
				cargo.Finish_Product = cargo.Finish_Product - t1
				cargo.RoughCast = cargo.RoughCast - t2
				cargo.Second_Burn = cargo.Second_Burn - t3
				cargo.Once_Dip = cargo.Once_Dip - t4
				cargo.Once_Burn = cargo.Once_Burn - t5
				cargo.Green_Body = cargo.Green_Body - t6
				cargo.Time_Stamp = wei.Time_Stamp
				cargo.Diameter = wei.Diameter
				UpdateOne1(c,"CargoSummary",cargo,"_id",cargo.Id)
				break
			}
		default:
			{
				parts := strings.SplitN(wei.Process_Length, "(", 2)
				var tmp = wei.Diameter + parts[0]
				err = CargoSummary.FindOne(context.Background(), bson.M{"process_specifications": tmp}).Decode(&cargo)
				t1,_ := strconv.ParseFloat(fmt.Sprintf("%.1f",wei.Finish_Product ), 64)
				t2,_ :=strconv.ParseFloat(fmt.Sprintf("%.1f",wei.RoughCast ), 64)
				t3,_ :=strconv.ParseFloat(fmt.Sprintf("%.1f",wei.Second_Burn + wei.Second_Burn_Furnace ), 64)
				t4,_ :=strconv.ParseFloat(fmt.Sprintf("%.1f",wei.Once_Dip ), 64)
				t5,_ :=strconv.ParseFloat(fmt.Sprintf("%.1f",wei.Once_Burn), 64)
				t6,_ :=strconv.ParseFloat(fmt.Sprintf("%.1f", wei.Once_Burn_Furnace + wei.Green_Body), 64)
				cargo.Finish_Product = cargo.Finish_Product - t1
				cargo.RoughCast = cargo.RoughCast - t2
				cargo.Second_Burn = cargo.Second_Burn - t3
				cargo.Once_Dip = cargo.Once_Dip - t4
				cargo.Once_Burn = cargo.Once_Burn - t5
				cargo.Green_Body = cargo.Green_Body - t6
				cargo.Time_Stamp = wei.Time_Stamp
				cargo.Diameter = wei.Diameter
				UpdateOne1(c,"CargoSummary",cargo,"_id",cargo.Id)
				break
			}
		}
	}

	//汇总表更改完后删除数量表和重量表中对应的数据
	Result1,err:=collection.DeleteOne(context.Background(),bson.M{"_id": objID})
	if err != nil {
		log.Println(err)
	}
	fmt.Println("amount:----",Result1)
	Result2,err:=db.Collection("weight").DeleteOne(context.Background(),bson.M{"time_stamp":one.Time_Stamp})
	if err != nil {
		log.Println(err)
	}
	fmt.Println("weight:----",Result2)
	return "成功"
}
